package com.aiden.app.common.view

import android.content.Context
import android.support.v4.widget.NestedScrollView
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.webkit.WebView

/**
 * 监听滑动状态的ScrollView
 *
 * @author yanggeng
 * @date 2019/1/10 下午4:47
 */
class CustomScrollView : NestedScrollView {

    /**
     * Runnable执行延迟的时间（100ms）
     */
    private val delayMillis: Long = 100

    /**
     * 上次滑动时的时间毫秒值
     */
    private var lastScrollTime: Long = -1

    private var onScrollListener: OnScrollListener? = null
    private var onCustomScrollChangedListener: OnCustomScrollChangedListener? = null

    private val scrollerTask = object : Runnable {
        override fun run() {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastScrollTime > 100) {
                lastScrollTime = -1
                if (onScrollListener != null) {
                    onScrollListener!!.onStopScroll()
                }
            } else {
                postDelayed(this, delayMillis)
            }
        }
    }


    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    override fun requestChildFocus(child: View, focused: View) {
        if (focused is WebView)
            return
        super.requestChildFocus(child, focused)
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        super.onScrollChanged(l, t, oldl, oldt)
        if (onCustomScrollChangedListener != null) {
            onCustomScrollChangedListener!!.onScrollChanged(l, t, oldl, oldt)
        }

        if (lastScrollTime == -1L) {
            if (onScrollListener != null) {
                onScrollListener!!.onPreScroll()
            }
            postDelayed(scrollerTask, delayMillis)
        }
        lastScrollTime = System.currentTimeMillis()
    }

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_MOVE -> {
                if (onScrollListener != null) {
                    val contentHeight = getChildAt(0).height
                    val scrollHeight = height

                    val scrollY = scrollY
                    onScrollListener?.onScroll(scrollY)

                    if (scrollY + scrollHeight >= contentHeight || contentHeight <= scrollHeight) {
                        onScrollListener?.onScrollToBottom()
                    } else {
                        onScrollListener?.notBottom()
                    }

                    if (scrollY == 0) {
                        onScrollListener?.onScrollToTop()
                    }

                }
            }
        }
        val result = super.onTouchEvent(ev)
        requestDisallowInterceptTouchEvent(false)
        return result
    }

    fun setOnScrollListener(onScrollListener: OnScrollListener) {
        this.onScrollListener = onScrollListener
    }

    fun setOnCustomScrollChangedListener(onCustomScrollChangedListener: OnCustomScrollChangedListener) {
        this.onCustomScrollChangedListener = onCustomScrollChangedListener
    }

    interface OnScrollListener {
        fun onPreScroll()
        fun onStopScroll()
        fun onScrollToBottom()
        fun onScrollToTop()
        fun onScroll(scrollY: Int)
        fun notBottom()
    }

    interface OnCustomScrollChangedListener {
        fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int)
    }

    companion object {

        private val TAG = "HomeScrollView"
    }

    /**
     * 回弹效果
     */

    //    // 拖动的距离 size = 4 的意思 只允许拖动屏幕的1/4
    //    private static final int size = 3;
    //    private View inner;
    //    private float y;
    //    private Rect normal = new Rect();
    //
    //    @SuppressLint("MissingSuperCall")
    //    @Override
    //    protected void onFinishInflate() {
    //        if (getChildCount() > 0) {
    //            inner = getChildAt(0);
    //        }
    //    }
    //
    //    @Override
    //    public boolean onTouchEvent(MotionEvent ev) {
    //        if (inner == null) {
    //            return super.onTouchEvent(ev);
    //        } else {
    //            commOnTouchEvent(ev);
    //        }
    //        return super.onTouchEvent(ev);
    //    }
    //
    //    public void commOnTouchEvent(MotionEvent ev) {
    //        int action = ev.getAction();
    //        switch (action) {
    //            case MotionEvent.ACTION_DOWN:
    //                y = ev.getY();
    //                break;
    //            case MotionEvent.ACTION_UP:
    //                if (isNeedAnimation()) {
    //                    // Log.v("mlguitar", "will up and animation");
    //                    animation();
    //                }
    //                break;
    //            case MotionEvent.ACTION_MOVE:
    //                final float preY = y;
    //                float nowY = ev.getY();
    //                /**
    //                 * size=4 表示 拖动的距离为屏幕的高度的1/4
    //                 */
    //                int deltaY = (int) (preY - nowY) / size;
    //                // 滚动
    //                // scrollBy(0, deltaY);
    //
    //                y = nowY;
    //                // 当滚动到最上或者最下时就不会再滚动，这时移动布局
    //                if (isNeedMove()) {
    //                    if (normal.isEmpty()) {
    //                        // 保存正常的布局位置
    //                        normal.set(inner.getLeft(), inner.getTop(),
    //                                inner.getRight(), inner.getBottom());
    //                        return;
    //                    }
    //                    int yy = inner.getTop() - deltaY;
    //
    //                    // 移动布局
    //                    inner.layout(inner.getLeft(), yy, inner.getRight(),
    //                            inner.getBottom() - deltaY);
    //                }
    //                break;
    //            default:
    //                break;
    //        }
    //    }
    //
    //    // 开启动画移动
    //
    //    public void animation() {
    //        // 开启移动动画
    //        TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(),
    //                normal.top);
    //        ta.setDuration(200);
    //        inner.startAnimation(ta);
    //        // 设置回到正常的布局位置
    //        inner.layout(normal.left, normal.top, normal.right, normal.bottom);
    //        normal.setEmpty();
    //    }
    //
    //    // 是否需要开启动画
    //    public boolean isNeedAnimation() {
    //        return !normal.isEmpty();
    //    }
    //
    //    // 是否需要移动布局
    //    public boolean isNeedMove() {
    //        int offset = inner.getMeasuredHeight() - getHeight();
    //        int scrollY = getScrollY();
    //        if (scrollY == 0 || scrollY == offset) {
    //            return true;
    //        }
    //        return false;
    //    }


}
